import Radio from 'backbone.radio';

import ExpenseFormPopupView from "./ExpenseFormPopupView.js";

const ExpenseFormPopupViewWithFile = ExpenseFormPopupView.extend({
    getNextFile() {
        const facade = Radio.channel('facade');
        const linkedFilesIds = facade.request('get:linkedFiles');
        const orphanFiles = facade.request(
            'get:collection', 'attachments'
        ).filter(
            file => !linkedFilesIds.has(file.id)
        );
        return orphanFiles[0] || null;
    },
    onModalAfterNotifySuccess() {
        const nextFile = this.getNextFile();
        if (nextFile) {
            this.triggerMethod(
                'line:add',
                this,
                {
                    category: this.model.get('category'),
                    files: [nextFile.id],
                },
                true,
            );
        } else {
            this.triggerMethod('modal:close');
        }
    },
});

export default ExpenseFormPopupViewWithFile;
